package com.itheima.filter;

import com.alibaba.fastjson.JSONObject;
import com.itheima.pojo.Result;
import com.itheima.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
//@WebFilter("/*")
public class LoginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        //获取请求url
        String url = req.getRequestURI();
        log.info(""+url);
        //判断请求是否包含login，如果包含，说明是登陆操作，放行
        if (url.contains("login")){
            log.info("登录操作");
            chain.doFilter(request,response);
            return;
        }
        //获取请求头中的令牌
        String jwt = req.getHeader("token");
        if (!StringUtils.hasLength(jwt)){
            log.info("");
            Result error = Result.error("NOT LOGIN");
            //手动转换对象JSON格式
            String notLogin = JSONObject.toJSONString(error);
            //返回
            resp.getWriter().write(notLogin);
            return;
        }
        //解析token，如果解析失败，返回错误信息（未登录）快捷键alt+ctrl+t
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {//jwt解析失败
            e.printStackTrace();
            log.info("解析令牌失败，返回一个错误信息");
            Result error = Result.error("NOT LOGIN");
            //手动转换对象JSON格式
            String notLogin = JSONObject.toJSONString(error);
            //返回
            resp.getWriter().write(notLogin);
            return;
        }

        //放行
        log.info("令牌合法，放行");
        chain.doFilter(request,response);
    }
}
